// manager.js - 物资管理人员专属功能
console.log('manager.js loaded and executing...');

// 全局错误处理函数
window.handleError = function(error, context) {
    console.error(`Error in ${context}:`, error);
    showToast('error', `操作失败: ${error.message || '未知错误'}`);
};

// 输入验证函数
function validateQuantity(quantity, minQuantity = 0) {
    const num = parseInt(quantity);
    if (isNaN(num) || num < minQuantity) {
        throw new Error(`数量必须大于等于${minQuantity}`);
    }
    return num;
}

function validateDate(dateStr) {
    if (!dateStr) return null;
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) {
        throw new Error('无效的日期格式');
    }
    return dateStr;
}

function validateRequired(value, fieldName) {
    if (!value || value.trim() === '') {
        throw new Error(`${fieldName}不能为空`);
    }
    return value.trim();
}

// 辅助函数：获取物资统计数据
function getMaterialStats() {
    const inventory = window.mockData.inventory || [];
    let total = inventory.length;
    let lowStock = 0;
    let expiring = 0;
    let expired = 0;

    inventory.forEach(item => {
        const status = getItemStatus(item.quantity, item.minQuantity, item.expiryDate);
        if (status === '库存不足') {
            lowStock++;
        } else if (status === '临期') {
            expiring++;
        } else if (status === '已过期') {
            expired++;
        }
    });

    return { total, lowStock, expiring, expired };
}

// 辅助函数：获取急救车统计数据
function getAmbulanceStats() {
    const ambulances = window.mockData.ambulances || [];
    let available = 0;
    let inUse = 0;
    let underMaintenance = 0;

    ambulances.forEach(ambulance => {
        if (ambulance.status === '可用') {
            available++;
        } else if (ambulance.status === '使用中') {
            inUse++;
        } else if (ambulance.status === '维修中') {
            underMaintenance++;
        }
    });

    return { available, inUse, underMaintenance };
}

window.renderDashboardManager = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    // 计算物资统计数据
    const materialStats = getMaterialStats();
    // 计算急救车统计数据
    const ambulanceStats = getAmbulanceStats();

    contentArea.innerHTML = `
        <div class="container-fluid">
            <h2 class="mb-4">管理中心仪表盘</h2>

            <!-- 物资概览 -->
            <div class="card mb-4">
                <div class="card-header">物资概览</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <div class="card bg-primary text-white h-100">
                                <div class="card-body">
                                    <h5 class="card-title">总物资种类</h5>
                                    <p class="card-text fs-3">${materialStats.total}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card bg-danger text-white h-100">
                                <div class="card-body">
                                    <h5 class="card-title">库存不足物资</h5>
                                    <p class="card-text fs-3">${materialStats.lowStock}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card bg-warning text-dark h-100">
                                <div class="card-body">
                                    <h5 class="card-title">临期物资</h5>
                                    <p class="card-text fs-3">${materialStats.expiring}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card bg-dark text-white h-100">
                                <div class="card-body">
                                    <h5 class="card-title">已过期物资</h5>
                                    <p class="card-text fs-3">${materialStats.expired}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 急救车概览 -->
            <div class="card mb-4">
                <div class="card-header">急救车概览</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <div class="card bg-success text-white h-100">
                                <div class="card-body">
                                    <h5 class="card-title">可用急救车</h5>
                                    <p class="card-text fs-3">${ambulanceStats.available}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="card bg-info text-white h-100">
                                <div class="card-body">
                                    <h5 class="card-title">使用中急救车</h5>
                                    <p class="card-text fs-3">${ambulanceStats.inUse}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="card bg-danger text-white h-100">
                                <div class="card-body">
                                    <h5 class="card-title">维修中急救车</h5>
                                    <p class="card-text fs-3">${ambulanceStats.underMaintenance}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
};

// 物资管理人员模块渲染函数
window.renderManagerAmbulanceConfig = function() {
    const contentArea = document.getElementById('contentArea');
    const materialCtx = document.getElementById('materialChartContainer').getContext('2d');
    new Chart(materialCtx, {
        type: 'pie',
        data: {
            labels: ['总物资种类', '库存不足物资', '临期物资', '已过期物资'],
            datasets: [{
                data: [materialStats.total, materialStats.lowStock, materialStats.expiring, materialStats.expired],
                backgroundColor: [
                    'rgba(13, 110, 253, 0.7)', // Primary
                    'rgba(220, 53, 69, 0.7)',  // Danger
                    'rgba(255, 193, 7, 0.7)',  // Warning
                    'rgba(52, 58, 64, 0.7)'   // Dark
                ],
                borderColor: [
                    'rgba(13, 110, 253, 1)',
                    'rgba(220, 53, 69, 1)',
                    'rgba(255, 193, 7, 1)',
                    'rgba(52, 58, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: '物资统计概览'
                }
            }
        }
    });

    // 渲染急救车统计饼图
    const ambulanceCtx = document.getElementById('ambulanceChartContainer').getContext('2d');
    new Chart(ambulanceCtx, {
        type: 'pie',
        data: {
            labels: ['可用急救车', '使用中急救车', '维修中急救车'],
            datasets: [{
                data: [ambulanceStats.available, ambulanceStats.inUse, ambulanceStats.underMaintenance],
                backgroundColor: [
                    'rgba(25, 135, 84, 0.7)',  // Success
                    'rgba(13, 202, 240, 0.7)', // Info
                    'rgba(220, 53, 69, 0.7)'   // Danger
                ],
                borderColor: [
                    'rgba(25, 135, 84, 1)',
                    'rgba(13, 202, 240, 1)',
                    'rgba(220, 53, 69, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: '急救车状态概览'
                }
            }
        }
    });
};

// 物资管理人员模块渲染函数
window.renderManagerAmbulanceConfig = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) {
        console.error('Error: contentArea element not found in renderManagerAmbulanceConfig.');
        return;
    }
    console.log('renderManagerAmbulanceConfig function called.');

    // 获取所有急救车数据
    const ambulances = window.mockData.ambulances || [];
    console.log('Ambulances data for rendering:', ambulances);

    if (ambulances.length === 0) {
        contentArea.innerHTML = `
            <div class="container-fluid">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>急救车物资配置</h2>
                    <button class="btn btn-primary" onclick="addNewAmbulance()">
                        <i class="fas fa-plus"></i> 新增急救车
                    </button>
                </div>
                <div class="alert alert-info" role="alert">
                    暂无急救车数据，请点击"新增急救车"按钮添加。
                </div>
            </div>
        `;
        console.log('No ambulances data to display.');
        return;
    }

    contentArea.innerHTML = `
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>急救车物资配置</h2>
                <button class="btn btn-primary" onclick="addNewAmbulance()">
                    <i class="fas fa-plus"></i> 新增急救车
                </button>
            </div>

            <!-- 急救车列表 -->
            <div class="row" id="ambulanceList">
                ${ambulances.map(ambulance => `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">${ambulance.plateNumber}</h5>
                                <span class="badge ${getStatusBadgeClass(ambulance.status)}">${ambulance.status}</span>
                            </div>
                            <div class="card-body">
                                <p><strong>所属科室：</strong>${ambulance.department}</p>
                                <p><strong>位置：</strong>${ambulance.location}</p>
                                <p><strong>物资状态：</strong>${getAmbulanceOverallSupplyStatus(ambulance)}</p>
                                <div class="mt-3">
                                    <button class="btn btn-info btn-sm me-2" onclick="viewAmbulanceDetails('${ambulance.id}')">
                                        <i class="fas fa-eye"></i> 查看详情
                                    </button>
                                    <button class="btn btn-warning btn-sm" onclick="editAmbulanceConfig('${ambulance.id}')">
                                        <i class="fas fa-edit"></i> 编辑配置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>

        <!-- 急救车详情模态框 -->
        <div class="modal fade" id="ambulanceDetailsModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">急救车物资详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body" id="ambulanceDetailsContent">
                        <!-- 详情内容将通过JavaScript动态填充 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑配置模态框 -->
        <div class="modal fade" id="editConfigModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑急救车配置</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body" id="editConfigContent">
                        <!-- 编辑表单将通过JavaScript动态填充 -->
                    </div>
                </div>
            </div>
        </div>
    `;

    // 初始化Bootstrap模态框
    new bootstrap.Modal(document.getElementById('ambulanceDetailsModal'));
    new bootstrap.Modal(document.getElementById('editConfigModal'));
};

// 获取状态对应的Bootstrap徽章样式
function getStatusBadgeClass(status) {
    switch (status) {
        case '可用':
            return 'bg-success';
        case '使用中':
            return 'bg-warning';
        case '维修中':
            return 'bg-danger';
        case '充足':
            return 'bg-success';
        case '存在临期物资':
            return 'bg-warning';
        case '物资不足':
            return 'bg-danger';
        case '存在过期物资':
            return 'bg-dark'; // 用深色表示过期，需要注意css里是否有这个颜色
        case '正常':
            return 'bg-success';
        case '临期':
            return 'bg-warning';
        case '已过期':
            return 'bg-dark';
        case '库存不足':
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
}

// 辅助函数：根据数量、最低库存和有效期判断物资状态
function getItemStatus(quantity, minQuantity, expiryDateStr) {
    if (quantity < minQuantity) {
        return '库存不足';
    }

    const expiryDate = new Date(expiryDateStr);
    const today = new Date();
    today.setHours(0, 0, 0, 0); // Normalize today to start of day

    if (expiryDate < today) {
        return '已过期';
    }

    const thirtyDaysLater = new Date(today);
    thirtyDaysLater.setDate(today.getDate() + 30);

    if (expiryDate <= thirtyDaysLater) {
        return '临期';
    }

    return '正常';
}

// 获取急救车整体物资状态
function getAmbulanceOverallSupplyStatus(ambulance) {
    let hasExpired = false;
    let hasInsufficient = false;
    let hasApproachingExpiry = false;

    for (const layer of ambulance.layers) {
        for (const item of layer.items) {
            const currentStatus = getItemStatus(item.quantity, item.minQuantity, item.expiryDate);
            if (currentStatus === '已过期') {
                hasExpired = true;
                break; 
            } else if (currentStatus === '库存不足') {
                hasInsufficient = true;
            } else if (currentStatus === '临期') {
                hasApproachingExpiry = true;
            }
        }
        if (hasExpired) break; 
    }

    if (hasExpired) {
        return '存在过期物资';
    } else if (hasInsufficient) {
        return '物资不足';
    } else if (hasApproachingExpiry) {
        return '存在临期物资';
    } else {
        return '充足';
    }
}

// 查看急救车详情
function viewAmbulanceDetails(ambulanceId) {
    const ambulance = window.mockData.ambulances.find(a => a.id === ambulanceId);
    if (!ambulance) return;

    const detailsContent = document.getElementById('ambulanceDetailsContent');
    detailsContent.innerHTML = `
        <div class="mb-3">
            <h6>基本信息</h6>
            <p><strong>车牌号：</strong>${ambulance.plateNumber}</p>
            <p><strong>所属科室：</strong>${ambulance.department}</p>
            <p><strong>位置：</strong>${ambulance.location}</p>
            <p><strong>状态：</strong>${ambulance.status}</p>
        </div>
        <div class="mb-3">
            <h6>物资配置</h6>
            ${ambulance.layers.map(layer => `
                <div class="card mb-3">
                    <div class="card-header">
                        <h6 class="mb-0">${layer.name} - ${layer.description}</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>物资名称</th>
                                        <th>当前数量</th>
                                        <th>最低库存</th>
                                        <th>有效期</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${layer.items.map(item => `
                                        <tr>
                                            <td>${item.name}</td>
                                            <td>${item.quantity}</td>
                                            <td>${item.minQuantity}</td>
                                            <td>${item.expiryDate}</td>
                                            <td><span class="badge ${getStatusBadgeClass(item.status)}">${item.status}</span></td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;

    const modal = new bootstrap.Modal(document.getElementById('ambulanceDetailsModal'));
    modal.show();
}

// 编辑急救车配置
function editAmbulanceConfig(ambulanceId) {
    const ambulance = window.mockData.ambulances.find(a => a.id === ambulanceId);
    if (!ambulance) return;

    const editContent = document.getElementById('editConfigContent');
    editContent.innerHTML = `
        <form id="editAmbulanceForm">
            <input type="hidden" id="ambulanceId" value="${ambulance.id}">
            <div class="mb-3">
                <label class="form-label">基本信息</label>
                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label">车牌号</label>
                        <input type="text" class="form-control" id="plateNumber" value="${ambulance.plateNumber}" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">所属科室</label>
                        <input type="text" class="form-control" id="department" value="${ambulance.department}" required>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-6">
                        <label class="form-label">位置</label>
                        <input type="text" class="form-control" id="location" value="${ambulance.location}" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">状态</label>
                        <select class="form-select" id="status" required>
                            <option value="可用" ${ambulance.status === '可用' ? 'selected' : ''}>可用</option>
                            <option value="使用中" ${ambulance.status === '使用中' ? 'selected' : ''}>使用中</option>
                            <option value="维修中" ${ambulance.status === '维修中' ? 'selected' : ''}>维修中</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label">层级配置</label>
                <div id="layersContainer">
                    ${ambulance.layers.map((layer, index) => `
                        <div class="card mb-3 layer-item">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">层级 ${index + 1}</h6>
                                <button type="button" class="btn btn-danger btn-sm" onclick="removeLayer(this)">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">层级名称</label>
                                        <input type="text" class="form-control layer-name" value="${layer.name}" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">描述</label>
                                        <input type="text" class="form-control layer-description" value="${layer.description}" required>
                                    </div>
                                </div>
                                <div class="mt-3">
                                    <h6>物资列表</h6>
                                    <div class="items-container">
                                        ${layer.items.map(item => `
                                            <div class="input-group mb-2 item-row">
                                                <input type="text" class="form-control item-name" placeholder="物资名称" value="${item.name}" required>
                                                <input type="number" class="form-control item-quantity" placeholder="数量" value="${item.quantity}" required>
                                                <input type="number" class="form-control item-min-quantity" placeholder="最低库存" value="${item.minQuantity}" required>
                                                <input type="date" class="form-control item-expiry" value="${item.expiryDate}" required>
                                                <button type="button" class="btn btn-danger" onclick="removeItem(this)">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </div>
                                        `).join('')}
                                    </div>
                                    <button type="button" class="btn btn-success btn-sm mt-2" onclick="addItem(this)">
                                        <i class="fas fa-plus"></i> 添加物资
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <button type="button" class="btn btn-primary mt-2" onclick="addLayer()">
                    <i class="fas fa-plus"></i> 添加层级
                </button>
            </div>

            <div class="text-end">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">保存更改</button>
            </div>
        </form>
    `;

    const modal = new bootstrap.Modal(document.getElementById('editConfigModal'));
    modal.show();

    // 绑定表单提交事件
    document.getElementById('editAmbulanceForm').addEventListener('submit', saveAmbulanceConfig);
}

// 添加新层级
function addLayer() {
    const layersContainer = document.getElementById('layersContainer');
    const layerCount = layersContainer.children.length;
    
    const newLayer = document.createElement('div');
    newLayer.className = 'card mb-3 layer-item';
    newLayer.innerHTML = `
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="mb-0">层级 ${layerCount + 1}</h6>
            <button type="button" class="btn btn-danger btn-sm" onclick="removeLayer(this)">
                <i class="fas fa-trash"></i>
            </button>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <label class="form-label">层级名称</label>
                    <input type="text" class="form-control layer-name" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">描述</label>
                    <input type="text" class="form-control layer-description" required>
                </div>
            </div>
            <div class="mt-3">
                <h6>物资列表</h6>
                <div class="items-container">
                </div>
                <button type="button" class="btn btn-success btn-sm mt-2" onclick="addItem(this)">
                    <i class="fas fa-plus"></i> 添加物资
                </button>
            </div>
        </div>
    `;
    
    layersContainer.appendChild(newLayer);
}

// 移除层级
function removeLayer(button) {
    const layerItem = button.closest('.layer-item');
    layerItem.remove();
    updateLayerNumbers();
}

// 更新层级编号
function updateLayerNumbers() {
    const layers = document.querySelectorAll('.layer-item');
    layers.forEach((layer, index) => {
        layer.querySelector('h6').textContent = `层级 ${index + 1}`;
    });
}

// 添加物资项
function addItem(button) {
    const itemsContainer = button.previousElementSibling;
    const newItem = document.createElement('div');
    newItem.className = 'input-group mb-2 item-row';
    newItem.innerHTML = `
        <input type="text" class="form-control item-name" placeholder="物资名称" required>
        <input type="number" class="form-control item-quantity" placeholder="数量" required>
        <input type="number" class="form-control item-min-quantity" placeholder="最低库存" required>
        <input type="date" class="form-control item-expiry" required>
        <button type="button" class="btn btn-danger" onclick="removeItem(this)">
            <i class="fas fa-times"></i>
        </button>
    `;
    itemsContainer.appendChild(newItem);
}

// 移除物资项
function removeItem(button) {
    button.closest('.item-row').remove();
}

// 保存急救车配置
function saveAmbulanceConfig(event) {
    event.preventDefault();
    
    const ambulanceId = document.getElementById('ambulanceId').value;
    const ambulance = window.mockData.ambulances.find(a => a.id === ambulanceId);
    if (!ambulance) return;

    // 更新基本信息
    ambulance.plateNumber = document.getElementById('plateNumber').value;
    ambulance.department = document.getElementById('department').value;
    ambulance.location = document.getElementById('location').value;
    ambulance.status = document.getElementById('status').value;

    // 更新层级和物资信息
    ambulance.layers = Array.from(document.querySelectorAll('.layer-item')).map(layer => {
        const items = Array.from(layer.querySelectorAll('.item-row')).map(item => ({
            id: 'I' + Date.now() + Math.random().toString(36).substr(2, 3),
            name: item.querySelector('.item-name').value,
            quantity: parseInt(item.querySelector('.item-quantity').value),
            minQuantity: parseInt(item.querySelector('.item-min-quantity').value),
            expiryDate: item.querySelector('.item-expiry').value,
            status: getItemStatus(parseInt(item.querySelector('.item-quantity').value), parseInt(item.querySelector('.item-min-quantity').value), item.querySelector('.item-expiry').value)
        }));

        return {
            id: 'L' + Date.now() + Math.random().toString(36).substr(2, 3),
            name: layer.querySelector('.layer-name').value,
            description: layer.querySelector('.layer-description').value,
            items: items
        };
    });

    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('editConfigModal'));
    modal.hide();

    // 刷新页面显示
    renderManagerAmbulanceConfig();

    // 显示成功提示
    showToast('success', '急救车配置已更新');
}

// 添加新急救车
function addNewAmbulance() {
    const newAmbulance = {
        id: 'A' + Date.now(),
        plateNumber: '新急救车',
        department: '',
        status: '可用',
        location: '',
        layers: []
    };

    if (!window.mockData.ambulances) {
        window.mockData.ambulances = [];
    }
    window.mockData.ambulances.push(newAmbulance);

    // 打开编辑模态框
    editAmbulanceConfig(newAmbulance.id);
}

// 显示提示消息
function showToast(type, message) {
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

// 创建提示消息容器
function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
    document.body.appendChild(container);
    return container;
}

window.renderManagerMaterialInfoManagement = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    contentArea.innerHTML = `
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>物资信息管理</h2>
                <div>
                    <button class="btn btn-primary me-2" onclick="showNewMaterialModal()">
                        <i class="fas fa-plus"></i> 新增物资
                    </button>
                    <button class="btn btn-info" onclick="exportMaterialInfoReport()">
                        <i class="fas fa-download me-2"></i>导出报告
                    </button>
                </div>
            </div>

            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" id="materialSearchInput" 
                                    placeholder="搜索物资名称、编号...">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <select class="form-select" id="materialCategoryFilter">
                                <option value="all">所有类别</option>
                                <option value="急救药品">急救药品</option>
                                <option value="基础药品">基础药品</option>
                                <option value="医疗设备">医疗设备</option>
                                <option value="手术器械">手术器械</option>
                                <option value="消毒用品">消毒用品</option>
                                <option value="手术耗材">手术耗材</option>
                                <option value="医疗耗材">医疗耗材</option>
                                <option value="儿科药品">儿科药品</option>
                                <option value="儿科设备">儿科设备</option>
                            </select>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="min-width: 120px; white-space: nowrap;">物资编号</th>
                                    <th>物资名称</th>
                                    <th>类别</th>
                                    <th>单位</th>
                                    <th>有效期至</th>
                                    <th>供应商</th>
                                    <th>存放位置</th>
                                    <th>备注</th>
                                    <th style="min-width: 120px; white-space: nowrap;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="materialListTableBody">
                                <!-- 物资列表将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新增/编辑物资模态框 (保持所有字段，以便编辑物资的基本属性)-->
        <div class="modal fade" id="materialModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="materialModalTitle">新增物资</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="materialForm">
                            <input type="hidden" id="materialId">
                            <div class="mb-3">
                                <label class="form-label">物资名称</label>
                                <input type="text" class="form-control" id="materialName" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">物资类别</label>
                                <select class="form-select" id="materialCategory" required>
                                    <option value="">请选择类别</option>
                                    <option value="急救药品">急救药品</option>
                                    <option value="基础药品">基础药品</option>
                                    <option value="医疗设备">医疗设备</option>
                                    <option value="手术器械">手术器械</option>
                                    <option value="消毒用品">消毒用品</option>
                                    <option value="手术耗材">手术耗材</option>
                                    <option value="医疗耗材">医疗耗材</option>
                                    <option value="儿科药品">儿科药品</option>
                                    <option value="儿科设备">儿科设备</option>
                                </select>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">库存</label>
                                    <input type="number" class="form-control" id="materialQuantity" required min="0">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">最低</label>
                                    <input type="number" class="form-control" id="materialMinQuantity" required min="0">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">计量单位</label>
                                    <input type="text" class="form-control" id="materialUnit" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">有效期至</label>
                                <input type="date" class="form-control" id="materialExpiryDate">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">供应商</label>
                                <input type="text" class="form-control" id="materialSupplier">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">存放位置</label>
                                <input type="text" class="form-control" id="materialLocation">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">备注</label>
                                <input type="text" class="form-control" id="materialNotes">
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveMaterial()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 初始化Bootstrap模态框
    new bootstrap.Modal(document.getElementById('materialModal'));

    // 绑定事件监听器
    document.getElementById('materialSearchInput').addEventListener('keyup', filterMaterials);
    document.getElementById('materialCategoryFilter').addEventListener('change', filterMaterials);

    // 加载物资列表
    loadMaterialList();
};

// 加载物资列表
function loadMaterialList() {
    const tbody = document.getElementById('materialListTableBody');
    if (!tbody) return;

    const materials = window.mockData.inventory || [];
    tbody.innerHTML = materials.map(material => `
        <tr>
            <td>${material.id}</td>
            <td>${material.name}</td>
            <td>${material.category}</td>
            <td>${material.unit}</td>
            <td>${material.expiryDate ? new Date(material.expiryDate).toLocaleDateString() : '未指定'}</td>
            <td>${material.supplier || '未指定'}</td>
            <td>${material.location || '未指定'}</td>
            <td>${material.notes || '无'}</td>
            <td>
                <button class="btn btn-sm btn-info me-1" onclick="editMaterial('${material.id}')">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteMaterial('${material.id}')">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </td>
        </tr>
    `).join('');
}

// 筛选物资列表
function filterMaterials() {
    const searchTerm = document.getElementById('materialSearchInput').value.toLowerCase();
    const categoryFilter = document.getElementById('materialCategoryFilter').value;

    const tbody = document.getElementById('materialListTableBody');
    if (!tbody) return;

    const rows = tbody.getElementsByTagName('tr');
    Array.from(rows).forEach(row => {
        const itemId = row.cells[0].textContent.toLowerCase();
        const itemName = row.cells[1].textContent.toLowerCase();
        const itemCategory = row.cells[2].textContent;

        const matchesSearch = itemName.includes(searchTerm) || itemId.includes(searchTerm);
        const matchesCategory = categoryFilter === 'all' || itemCategory === categoryFilter;
        
        row.style.display = matchesSearch && matchesCategory ? '' : 'none';
    });
}

// 显示新增物资模态框
function showNewMaterialModal() {
    document.getElementById('materialModalTitle').textContent = '新增物资';
    document.getElementById('materialForm').reset();
    document.getElementById('materialId').value = '';
    
    // 确保供应商和备注字段在模态框中可见
    document.getElementById('materialSupplier').value = '';
    document.getElementById('materialNotes').value = '';
    // 重置库存和最低库存，如果需要
    document.getElementById('materialQuantity').value = 0;
    document.getElementById('materialMinQuantity').value = 0;

    const modal = new bootstrap.Modal(document.getElementById('materialModal'));
    modal.show();
}

// 编辑物资
function editMaterial(materialId) {
    const material = window.mockData.inventory.find(m => m.id === materialId);
    if (!material) return;

    document.getElementById('materialModalTitle').textContent = '编辑物资';
    document.getElementById('materialId').value = material.id;
    document.getElementById('materialName').value = material.name;
    document.getElementById('materialCategory').value = material.category;
    document.getElementById('materialQuantity').value = material.quantity;
    document.getElementById('materialMinQuantity').value = material.minQuantity;
    document.getElementById('materialUnit').value = material.unit;
    document.getElementById('materialExpiryDate').value = material.expiryDate ? material.expiryDate.split('T')[0] : '';
    document.getElementById('materialSupplier').value = material.supplier || '';
    document.getElementById('materialLocation').value = material.location || '';
    document.getElementById('materialNotes').value = material.notes || '';

    const modal = new bootstrap.Modal(document.getElementById('materialModal'));
    modal.show();
}

// 保存物资信息
function saveMaterial() {
    try {
        const form = document.getElementById('materialForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        const materialId = document.getElementById('materialId').value;
        const material = {
            id: materialId || 'I' + Date.now(),
            name: validateRequired(document.getElementById('materialName').value, '物资名称'),
            category: validateRequired(document.getElementById('materialCategory').value, '物资类别'),
            quantity: validateQuantity(document.getElementById('materialQuantity').value),
            minQuantity: validateQuantity(document.getElementById('materialMinQuantity').value),
            unit: validateRequired(document.getElementById('materialUnit').value, '计量单位'),
            expiryDate: validateDate(document.getElementById('materialExpiryDate').value),
            supplier: document.getElementById('materialSupplier').value || null,
            location: document.getElementById('materialLocation').value || null,
            notes: document.getElementById('materialNotes').value || null,
            status: getItemStatus(
                parseInt(document.getElementById('materialQuantity').value),
                parseInt(document.getElementById('materialMinQuantity').value),
                document.getElementById('materialExpiryDate').value
            )
        };

        if (!window.mockData.inventory) {
            window.mockData.inventory = [];
        }

        const existingIndex = window.mockData.inventory.findIndex(m => m.id === materialId);
        if (existingIndex >= 0) {
            window.mockData.inventory[existingIndex] = material;
        } else {
            window.mockData.inventory.push(material);
        }

        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('materialModal'));
        modal.hide();

        // 刷新列表
        loadMaterialList();
        showToast('success', materialId ? '物资信息已更新' : '新物资已添加');
    } catch (error) {
        handleError(error, '保存物资信息');
    }
}

// 删除物资
function deleteMaterial(materialId) {
    if (!confirm('确定要删除这个物资吗？此操作不可恢复。')) {
        return;
    }

    const index = window.mockData.inventory.findIndex(m => m.id === materialId);
    if (index >= 0) {
        window.mockData.inventory.splice(index, 1);
        loadMaterialList();
        showToast('success', '物资已删除');
    }
}

// 导出物资信息报告
function exportMaterialInfoReport() {
    const materials = window.mockData.inventory || [];
    exportToCSV(materials, `物资信息报告_${new Date().toLocaleDateString()}.csv`);
}

window.renderManagerInventoryManagement = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    contentArea.innerHTML = `
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>物资库存管理</h2>
                <button class="btn btn-primary" onclick="exportInventoryReport()">
                    <i class="fas fa-download me-2"></i>导出库存报告
                </button>
            </div>

            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-5">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" id="inventorySearchInput" 
                                    placeholder="搜索物资名称、编号、位置...">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <select class="form-select" id="inventoryCategoryFilter">
                                <option value="all">所有类别</option>
                                <option value="急救药品">急救药品</option>
                                <option value="基础药品">基础药品</option>
                                <option value="医疗设备">医疗设备</option>
                                <option value="手术器械">手术器械</option>
                                <option value="消毒用品">消毒用品</option>
                                <option value="手术耗材">手术耗材</option>
                                <option value="医疗耗材">医疗耗材</option>
                                <option value="儿科药品">儿科药品</option>
                                <option value="儿科设备">儿科设备</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="inventoryStatusFilter">
                                <option value="all">所有状态</option>
                                <option value="正常">正常</option>
                                <option value="临期">临期</option>
                                <option value="已过期">已过期</option>
                                <option value="库存不足">库存不足</option>
                            </select>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="min-width: 120px; white-space: nowrap;">物资编号</th>
                                    <th>物资名称</th>
                                    <th>类别</th>
                                    <th>库存量</th>
                                    <th>单位</th>
                                    <th>最低库存</th>
                                    <th>有效期至</th>
                                    <th>存放位置</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="inventoryListTableBody">
                                <!-- 库存列表将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑库存模态框 -->
        <div class="modal fade" id="editInventoryModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑库存</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editInventoryForm">
                            <input type="hidden" id="inventoryMaterialId">
                            <div class="mb-3">
                                <label class="form-label">物资名称</label>
                                <input type="text" class="form-control" id="inventoryMaterialName" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">当前库存量</label>
                                <input type="number" class="form-control" id="currentInventoryQuantity" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">调整库存量</label>
                                <input type="number" class="form-control" id="adjustedInventoryQuantity" required min="0">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">操作类型</label>
                                <select class="form-select" id="inventoryOperationType" required>
                                    <option value="">请选择</option>
                                    <option value="入库">入库</option>
                                    <option value="出库">出库</option>
                                    <option value="盘点调整">盘点调整</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">备注</label>
                                <textarea class="form-control" id="inventoryOperationNotes" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveInventoryAdjustment()">保存更改</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 初始化Bootstrap模态框
    new bootstrap.Modal(document.getElementById('editInventoryModal'));

    // 绑定事件监听器
    document.getElementById('inventorySearchInput').addEventListener('keyup', filterInventory);
    document.getElementById('inventoryCategoryFilter').addEventListener('change', filterInventory);
    document.getElementById('inventoryStatusFilter').addEventListener('change', filterInventory);

    // 加载库存列表
    loadInventoryList();
};

// 加载库存列表
function loadInventoryList() {
    const tbody = document.getElementById('inventoryListTableBody');
    if (!tbody) return;

    const inventoryItems = window.mockData.inventory || [];
    tbody.innerHTML = inventoryItems.map(item => `
        <tr>
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.category}</td>
            <td>${item.quantity}</td>
            <td>${item.unit}</td>
            <td>${item.minQuantity}</td>
            <td>${item.expiryDate ? new Date(item.expiryDate).toLocaleDateString() : '未指定'}</td>
            <td>${item.location || '未指定'}</td>
            <td><span class="badge ${getStatusBadgeClass(item.status)}">${item.status}</span></td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editInventory('${item.id}')">
                    <i class="fas fa-edit"></i> 调整库存
                </button>
            </td>
        </tr>
    `).join('');
}

// 筛选库存列表
function filterInventory() {
    const searchTerm = document.getElementById('inventorySearchInput').value.toLowerCase();
    const categoryFilter = document.getElementById('inventoryCategoryFilter').value;
    const statusFilter = document.getElementById('inventoryStatusFilter').value;

    const tbody = document.getElementById('inventoryListTableBody');
    if (!tbody) return;

    const rows = tbody.getElementsByTagName('tr');
    Array.from(rows).forEach(row => {
        const itemId = row.cells[0].textContent.toLowerCase();
        const itemName = row.cells[1].textContent.toLowerCase();
        const itemCategory = row.cells[2].textContent;
        const itemLocation = row.cells[7].textContent.toLowerCase();
        const itemStatus = row.cells[8].textContent.trim();

        const matchesSearch = itemName.includes(searchTerm) || itemId.includes(searchTerm) || itemLocation.includes(searchTerm);
        const matchesCategory = categoryFilter === 'all' || itemCategory === categoryFilter;
        const matchesStatus = statusFilter === 'all' || itemStatus === statusFilter;

        row.style.display = matchesSearch && matchesCategory && matchesStatus ? '' : 'none';
    });
}

// 编辑库存模态框
function editInventory(materialId) {
    const material = window.mockData.inventory.find(m => m.id === materialId);
    if (!material) return;

    document.getElementById('inventoryMaterialId').value = material.id;
    document.getElementById('inventoryMaterialName').value = material.name;
    document.getElementById('currentInventoryQuantity').value = material.quantity;
    document.getElementById('adjustedInventoryQuantity').value = material.quantity; // 默认显示当前数量
    document.getElementById('inventoryOperationType').value = ''; // 重置操作类型
    document.getElementById('inventoryOperationNotes').value = ''; // 清空备注

    const modal = new bootstrap.Modal(document.getElementById('editInventoryModal'));
    modal.show();
}

// 保存库存调整
function saveInventoryAdjustment() {
    const form = document.getElementById('editInventoryForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const materialId = document.getElementById('inventoryMaterialId').value;
    const adjustedQuantity = parseInt(document.getElementById('adjustedInventoryQuantity').value);
    const operationType = document.getElementById('inventoryOperationType').value;
    const notes = document.getElementById('inventoryOperationNotes').value;

    const material = window.mockData.inventory.find(m => m.id === materialId);
    if (!material) return;

    const oldQuantity = material.quantity;
    let newQuantity = oldQuantity;

    if (operationType === '入库') {
        newQuantity += adjustedQuantity - oldQuantity; // 入库是增加量
    } else if (operationType === '出库') {
        newQuantity -= (adjustedQuantity - oldQuantity); // 出库是减少量
        if (newQuantity < 0) {
            showToast('error', '出库数量不能大于当前库存！');
            return;
        }
    } else if (operationType === '盘点调整') {
        newQuantity = adjustedQuantity; // 盘点调整直接设为新值
    }

    material.quantity = newQuantity;
    material.status = getItemStatus(material.quantity, material.minQuantity, material.expiryDate); // 更新状态

    // 记录库存操作历史
    if (!window.mockData.inventoryRecords) {
        window.mockData.inventoryRecords = [];
    }
    window.mockData.inventoryRecords.unshift({
        id: 'IR' + Date.now(),
        materialId: material.id,
        materialName: material.name,
        operationType: operationType,
        oldQuantity: oldQuantity,
        newQuantity: newQuantity,
        adjustedAmount: newQuantity - oldQuantity,
        operator: '管理员', // 假设操作员是管理员
        operationTime: new Date().toISOString().slice(0, 16),
        notes: notes
    });

    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('editInventoryModal'));
    modal.hide();

    // 刷新列表
    loadInventoryList();
    showToast('success', '库存调整成功！');
}

// 导出库存报告
function exportInventoryReport() {
    const inventory = window.mockData.inventory || [];
    exportToCSV(inventory, `库存报告_${new Date().toLocaleDateString()}.csv`);
}

/**
 * 盘点记录模块渲染函数
 * 实现功能：可对物资进行盘点并进行相应记录，可对盘点情况进行监督
 */
window.renderManagerInventoryRecords = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    // 构建盘点记录页面HTML结构
    contentArea.innerHTML = `
        <div class="container-fluid">
            <!-- 页面标题和导出按钮 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>盘点记录</h2>
                <button class="btn btn-primary" onclick="exportInventoryRecordsReport()">
                    <i class="fas fa-download me-2"></i>导出报告
                </button>
            </div>

            <div class="card">
                <div class="card-body">
                    <!-- 搜索和筛选区域 -->
                    <div class="row mb-3">
                        <div class="col-md-5">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" id="inventoryRecordSearchInput" 
                                    placeholder="搜索物资名称、记录编号...">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <select class="form-select" id="inventoryRecordOperationTypeFilter">
                                <option value="all">所有操作类型</option>
                                <option value="入库">入库</option>
                                <option value="出库">出库</option>
                                <option value="盘点调整">盘点调整</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <input type="text" class="form-control" id="inventoryRecordOperatorFilter" 
                                placeholder="按操作员筛选">
                        </div>
                    </div>

                    <!-- 盘点记录表格 -->
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="min-width: 120px; white-space: nowrap;">记录编号</th>
                                    <th>物资名称</th>
                                    <th>操作类型</th>
                                    <th>原库存</th>
                                    <th>新库存</th>
                                    <th>调整数量</th>
                                    <th>操作员</th>
                                    <th style="min-width: 150px; white-space: nowrap;">操作时间</th>
                                    <th>备注</th>
                                </tr>
                            </thead>
                            <tbody id="inventoryRecordsTableBody">
                                <!-- 盘点记录将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 绑定事件监听器
    document.getElementById('inventoryRecordSearchInput').addEventListener('keyup', filterInventoryRecords);
    document.getElementById('inventoryRecordOperationTypeFilter').addEventListener('change', filterInventoryRecords);
    document.getElementById('inventoryRecordOperatorFilter').addEventListener('keyup', filterInventoryRecords);

    // 加载盘点记录列表
    loadInventoryRecordsList();
};

/**
 * 加载盘点记录列表
 * 从mockData中获取盘点记录数据并渲染到表格中
 */
function loadInventoryRecordsList() {
    const tbody = document.getElementById('inventoryRecordsTableBody');
    if (!tbody) return;

    const records = window.mockData.inventoryRecords || [];
    
    // 将记录数据转换为HTML表格行
    tbody.innerHTML = records.map(record => `
        <tr>
            <td>${record.id}</td>
            <td>${record.materialName}</td>
            <td>${record.operationType}</td>
            <td>${record.oldQuantity}</td>
            <td>${record.newQuantity}</td>
            <td>${record.adjustedAmount}</td>
            <td>${record.operator}</td>
            <td>${record.operationTime}</td>
            <td>${record.notes || '无'}</td>
        </tr>
    `).join('');
}

/**
 * 筛选盘点记录列表
 * 根据搜索词、操作类型和操作员进行多维度筛选
 */
function filterInventoryRecords() {
    const searchTerm = document.getElementById('inventoryRecordSearchInput').value.toLowerCase();
    const operationTypeFilter = document.getElementById('inventoryRecordOperationTypeFilter').value;
    const operatorFilter = document.getElementById('inventoryRecordOperatorFilter').value.toLowerCase();

    const tbody = document.getElementById('inventoryRecordsTableBody');
    if (!tbody) return;

    const rows = tbody.getElementsByTagName('tr');
    
    // 遍历表格行进行筛选
    Array.from(rows).forEach(row => {
        const recordId = row.cells[0].textContent.toLowerCase();        // 记录编号
        const materialName = row.cells[1].textContent.toLowerCase();    // 物资名称
        const operationType = row.cells[2].textContent;                 // 操作类型
        const operator = row.cells[6].textContent.toLowerCase();        // 操作员

        // 搜索条件匹配
        const matchesSearch = recordId.includes(searchTerm) || materialName.includes(searchTerm);
        // 操作类型匹配
        const matchesOperationType = operationTypeFilter === 'all' || operationType === operationTypeFilter;
        // 操作员匹配
        const matchesOperator = operator.includes(operatorFilter);

        // 显示或隐藏行
        row.style.display = matchesSearch && matchesOperationType && matchesOperator ? '' : 'none';
    });
}

/**
 * 导出盘点记录报告
 * 将盘点记录数据导出为CSV格式文件
 */
function exportInventoryRecordsReport() {
    const records = window.mockData.inventoryRecords || [];
    
    // 准备导出数据，添加中文列名
    const exportData = records.map(record => ({
        '记录编号': record.id,
        '物资名称': record.materialName,
        '操作类型': record.operationType,
        '原库存': record.oldQuantity,
        '新库存': record.newQuantity,
        '调整数量': record.adjustedAmount,
        '操作员': record.operator,
        '操作时间': record.operationTime,
        '备注': record.notes || '无'
    }));

    // 调用CSV导出函数
    exportToCSV(exportData, `盘点记录报告_${new Date().toLocaleDateString()}.csv`);
}

// 急救车补充管理模块渲染函数
window.renderManagerAmbulanceReplenishment = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    contentArea.innerHTML = `
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>急救车补充管理</h2>
                <button class="btn btn-primary" onclick="exportAmbulanceReplenishmentReport()">
                    <i class="fas fa-download me-2"></i>导出报告
                </button>
            </div>

            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" id="replenishmentSearchInput" 
                                    placeholder="搜索急救车编号、物资名称...">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <select class="form-select" id="replenishmentStatusFilter">
                                <option value="all">所有状态</option>
                                <option value="待处理">待处理</option>
                                <option value="已处理">已处理</option>
                            </select>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="min-width: 120px; white-space: nowrap;">急救车编号</th>
                                    <th>物资名称</th>
                                    <th>补充至层</th>
                                    <th>需求数量</th>
                                    <th>申请时间</th>
                                    <th>申请人</th>
                                    <th>状态</th>
                                    <th style="min-width: 100px; white-space: nowrap;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="replenishmentListTableBody">
                                <!-- 补充请求列表将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 补充物资模态框 -->
        <div class="modal fade" id="replenishModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">补充物资</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="replenishForm">
                            <input type="hidden" id="replenishmentRequestId">
                            <div class="mb-3">
                                <label class="form-label">急救车编号</label>
                                <input type="text" class="form-control" id="replenishAmbulancePlate" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">物资名称</label>
                                <input type="text" class="form-control" id="replenishMaterialName" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">需求数量</label>
                                <input type="number" class="form-control" id="replenishQuantityRequired" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">补充至层</label>
                                <input type="text" class="form-control" id="replenishTargetLayer" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">补充数量</label>
                                <input type="number" class="form-control" id="replenishQuantityActual" required min="1">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">备注</label>
                                <textarea class="form-control" id="replenishNotes" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="processReplenishment()">确认补充</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 初始化Bootstrap模态框
    new bootstrap.Modal(document.getElementById('replenishModal'));

    // 绑定事件监听器
    document.getElementById('replenishmentSearchInput').addEventListener('keyup', filterAmbulanceReplenishment);
    document.getElementById('replenishmentStatusFilter').addEventListener('change', filterAmbulanceReplenishment);

    // 加载补充请求列表
    loadAmbulanceReplenishmentList();
};

// 加载急救车补充请求列表
function loadAmbulanceReplenishmentList() {
    const tbody = document.getElementById('replenishmentListTableBody');
    if (!tbody) return;

    const requests = window.mockData.replenishmentRequests || [];
    tbody.innerHTML = requests.map(request => `
        <tr>
            <td>${request.ambulancePlate}</td>
            <td>${request.materialName}</td>
            <td>${request.targetLayer}</td>
            <td>${request.requiredQuantity}</td>
            <td>${request.applicationTime}</td>
            <td>${request.applicant}</td>
            <td><span class="badge ${getReplenishmentStatusBadgeClass(request.status)}">${request.status}</span></td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="showReplenishModal('${request.id}')" ${request.status === '已处理' ? 'disabled' : ''}>
                    <i class="fas fa-truck-loading"></i> 补充
                </button>
            </td>
        </tr>
    `).join('');
}

// 获取补充状态对应的Bootstrap徽章样式
function getReplenishmentStatusBadgeClass(status) {
    switch (status) {
        case '待处理':
            return 'bg-warning';
        case '已处理':
            return 'bg-success';
        default:
            return 'bg-secondary';
    }
}

// 筛选急救车补充请求列表
function filterAmbulanceReplenishment() {
    const searchTerm = document.getElementById('replenishmentSearchInput').value.toLowerCase();
    const statusFilter = document.getElementById('replenishmentStatusFilter').value;

    const tbody = document.getElementById('replenishmentListTableBody');
    if (!tbody) return;

    const rows = tbody.getElementsByTagName('tr');
    Array.from(rows).forEach(row => {
        const ambulancePlate = row.cells[0].textContent.toLowerCase();
        const materialName = row.cells[1].textContent.toLowerCase();
        const requestStatus = row.cells[6].textContent.trim();

        const matchesSearch = ambulancePlate.includes(searchTerm) || materialName.includes(searchTerm);
        const matchesStatus = statusFilter === 'all' || requestStatus === statusFilter;

        row.style.display = matchesSearch && matchesStatus ? '' : 'none';
    });
}

// 显示补充物资模态框
function showReplenishModal(requestId) {
    const request = window.mockData.replenishmentRequests.find(r => r.id === requestId);
    if (!request) return;

    document.getElementById('replenishmentRequestId').value = request.id;
    document.getElementById('replenishAmbulancePlate').value = request.ambulancePlate;
    document.getElementById('replenishMaterialName').value = request.materialName;
    document.getElementById('replenishQuantityRequired').value = request.requiredQuantity;
    document.getElementById('replenishTargetLayer').value = request.targetLayer || '';
    document.getElementById('replenishQuantityActual').value = request.requiredQuantity; // 默认补充数量为需求数量
    document.getElementById('replenishNotes').value = request.notes || '';

    const modal = new bootstrap.Modal(document.getElementById('replenishModal'));
    modal.show();
}

// 处理补充操作
function processReplenishment() {
    const form = document.getElementById('replenishForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const requestId = document.getElementById('replenishmentRequestId').value;
    const actualQuantity = parseInt(document.getElementById('replenishQuantityActual').value);
    const notes = document.getElementById('replenishNotes').value;

    const requestIndex = window.mockData.replenishmentRequests.findIndex(r => r.id === requestId);
    if (requestIndex === -1) return;

    const request = window.mockData.replenishmentRequests[requestIndex];
    request.status = '已处理';
    request.actualQuantity = actualQuantity; // 记录实际补充数量
    request.processedTime = new Date().toLocaleString(); // 记录处理时间
    request.processedBy = '管理员'; // 假设操作员是管理员
    request.notes = notes; // 更新备注

    // 假设补充物资会影响库存，这里需要添加逻辑更新库存，例如调用 saveInventoryAdjustment 或直接修改 inventory
    // 为了简化，这里仅更新补充请求的状态，实际项目中需要更复杂的库存扣减逻辑
    showToast('success', `补充请求 ${requestId} 已处理`);

    const modal = bootstrap.Modal.getInstance(document.getElementById('replenishModal'));
    modal.hide();

    loadAmbulanceReplenishmentList(); // 刷新列表
}

// 导出急救车补充报告
function exportAmbulanceReplenishmentReport() {
    const requests = window.mockData.replenishmentRequests || [];
    exportToCSV(requests, `急救车补充报告_${new Date().toLocaleDateString()}.csv`);
}

// 物资资料查询模块渲染函数
window.renderMaterialDataQuery = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    contentArea.innerHTML = `
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>物资资料查询</h2>
                <button class="btn btn-primary" onclick="exportMaterialDataReport()">
                    <i class="fas fa-download me-2"></i>导出报告
                </button>
            </div>

            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" id="materialDataSearchInput" 
                                    placeholder="搜索物资名称、编号...">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <select class="form-select" id="materialDataCategoryFilter">
                                <option value="all">所有类别</option>
                                <option value="急救药品">急救药品</option>
                                <option value="基础药品">基础药品</option>
                                <option value="医疗设备">医疗设备</option>
                                <option value="手术器械">手术器械</option>
                                <option value="消毒用品">消毒用品</option>
                                <option value="手术耗材">手术耗材</option>
                                <option value="医疗耗材">医疗耗材</option>
                                <option value="儿科药品">儿科药品</option>
                                <option value="儿科设备">儿科设备</option>
                            </select>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="min-width: 120px; white-space: nowrap;">物资编号</th>
                                    <th>物资名称</th>
                                    <th>类别</th>
                                    <th>当前库存</th>
                                    <th>最低库存</th>
                                    <th>有效期至</th>
                                    <th>供应商</th>
                                    <th>存放位置</th>
                                </tr>
                            </thead>
                            <tbody id="materialDataTableBody">
                                <!-- 物资资料将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 绑定事件监听器
    document.getElementById('materialDataSearchInput').addEventListener('keyup', filterMaterialData);
    document.getElementById('materialDataCategoryFilter').addEventListener('change', filterMaterialData);

    // 加载物资资料列表
    loadMaterialDataList();
};

// 加载物资资料列表
function loadMaterialDataList() {
    const tbody = document.getElementById('materialDataTableBody');
    if (!tbody) return;

    const materials = window.mockData.inventory || [];
    tbody.innerHTML = materials.map(material => `
        <tr>
            <td>${material.id}</td>
            <td>${material.name}</td>
            <td>${material.category}</td>
            <td>${material.quantity}</td>
            <td>${material.minQuantity}</td>
            <td>${material.expiryDate ? new Date(material.expiryDate).toLocaleDateString() : '未指定'}</td>
            <td>${material.supplier || '未指定'}</td>
            <td>${material.location || '未指定'}</td>
        </tr>
    `).join('');
}

// 筛选物资资料列表
function filterMaterialData() {
    const searchTerm = document.getElementById('materialDataSearchInput').value.toLowerCase();
    const categoryFilter = document.getElementById('materialDataCategoryFilter').value;

    const tbody = document.getElementById('materialDataTableBody');
    if (!tbody) return;

    const rows = tbody.getElementsByTagName('tr');
    Array.from(rows).forEach(row => {
        const itemId = row.cells[0].textContent.toLowerCase();
        const itemName = row.cells[1].textContent.toLowerCase();
        const itemCategory = row.cells[2].textContent;

        const matchesSearch = itemName.includes(searchTerm) || itemId.includes(searchTerm);
        const matchesCategory = categoryFilter === 'all' || itemCategory === categoryFilter;

        row.style.display = matchesSearch && matchesCategory ? '' : 'none';
    });
}

// 导出物资资料报告
function exportMaterialDataReport() {
    const materials = window.mockData.inventory || [];
    exportToCSV(materials, `物资资料报告_${new Date().toLocaleDateString()}.csv`);
}

// 导出数据工具函数
function exportToCSV(data, filename) {
    try {
        // 将数据转换为CSV格式
        const headers = Object.keys(data[0]);
        const csvContent = [
            headers.join(','),
            ...data.map(row => headers.map(header => {
                const value = row[header];
                // 处理包含逗号、引号或换行符的值
                if (value === null || value === undefined) return '';
                const stringValue = String(value);
                if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
                    return `"${stringValue.replace(/"/g, '""')}"`;
                }
                return stringValue;
            }).join(','))
        ].join('\n');

        // 创建Blob对象
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        
        // 创建下载链接
        const link = document.createElement('a');
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    } catch (error) {
        handleError(error, '导出数据');
    }
}

// 更新导出报告函数
function exportMaterialInfoReport() {
    const materials = window.mockData.inventory || [];
    exportToCSV(materials, `物资信息报告_${new Date().toLocaleDateString()}.csv`);
}

function exportInventoryReport() {
    const inventory = window.mockData.inventory || [];
    exportToCSV(inventory, `库存报告_${new Date().toLocaleDateString()}.csv`);
}

function exportInventoryRecordsReport() {
    const records = window.mockData.inventoryRecords || [];
    exportToCSV(records, `盘点记录报告_${new Date().toLocaleDateString()}.csv`);
}

function exportAmbulanceReplenishmentReport() {
    const requests = window.mockData.replenishmentRequests || [];
    exportToCSV(requests, `急救车补充报告_${new Date().toLocaleDateString()}.csv`);
}

function exportMaterialDataReport() {
    const materials = window.mockData.inventory || [];
    exportToCSV(materials, `物资资料报告_${new Date().toLocaleDateString()}.csv`);
} 